package com.site.common.config;

import com.site.common.R;
import com.site.common.annotation.IgnoreResponseDataAdvice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * <h1>处理自定义忽略响应注解 @IgnoreResponseDataAdvice</h1>
 */
@RestControllerAdvice("com.site.controller")
public class ResponseDataAdviceConfig implements ResponseBodyAdvice<Object> {

    private static final Logger logger = LoggerFactory.getLogger(ResponseDataAdviceConfig.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Class converterType) {
        // 如果当前类标识了自定义注解 @IgnoreResponseAdvice，不需要处理
        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseDataAdvice.class)){
            return false;
        }
        // 如果当前方法标识了自定义注解 @IgnoreResponseAdvice，不需要处理
        return methodParameter.getMethod() == null || !methodParameter.getMethod().isAnnotationPresent(IgnoreResponseDataAdvice.class);
    }

    /**
     * 最终响应返回之前的处理
     * @param body 当前响应对象
     * @param methodParameter
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 定义最终返回对象
        if (body == null){
            logger.info("地址:{},返回数据:{}",request.getURI(),body);
            return R.ok();
        }else if (body instanceof R){// 已经是 R，不需要处理
            logger.info("地址:{},返回数据:{}",request.getURI(),((R) body).getData());
            return body;
        }else if (body instanceof String){
            logger.info("地址:{},返回数据:{}",request.getURI(),body);
            return R.ok(body.toString());
        }else {// 否则把响应对象作为 R 的 data 部分
            logger.info("地址:{},返回数据:{}",request.getURI(),body);
            return R.ok(body);
        }
    }
}
